package com.RWM.activities;

import java.util.List;

import org.json.JSONObject;

import com.RWM.helpers.HelloItemizedOverlay;
import com.RWM.helpers.Zone;
import com.RWM.reference.Reference.RequestMethod;
import com.RWM.serverTools.Connect;
import com.facebook.android.Facebook;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class ZoneDetailActivity extends MapActivity implements OnClickListener {
	private Intent myIntent;
	private TextView tv;
	private Button btn_dir, btn_addMe, btn_post;
	private MapController mapController;
	private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in Meters
	private static final long MINIMUM_TIME_BETWEEN_UPDATES = 1000; // in Milliseconds
	protected LocationManager locationManager;
	private int pzoneID;
	private String access_token;
	private JSONObject jObject;
	private GeoPoint gp;
	Facebook facebook;
	MyLocationOverlay myLocationOverlay;
	RideWithMe context;
	/*
	Toast.makeText(ZoneDetailActivity.this, "ZONEID IS"+pzoneID ,
	Toast.LENGTH_LONG).show();
	 */
	/****************************************************************************/
	/* Mocked up data - THIS WILL SOON BE REPLACED WITH LIVE DATA FROM THE SERVER */
	private String lat = "33.864848"; //To come from the intent
	private String lon = "-84.477439"; //To come from the intent
	/****************************************************************************/
	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.map);
		
		context = (RideWithMe) getApplicationContext();
		facebook = context.getFacebook();

		/* Get the information passed from the prior activity/window */
		String description;
		myIntent = getIntent();
		Bundle extras = myIntent.getExtras();
		description = extras.getString("txt");
		pzoneID = extras.getInt("id");
		access_token = extras.getString("access_token");
	

		/* Set the text view to display zone name and initialize mapview */
		tv = (TextView) findViewById(R.id.map_textview);
		tv.setText(description);
		final MapView mapView = (MapView) findViewById(R.id.mapview);
		mapView.setBuiltInZoomControls(true);
		btn_dir = (Button) findViewById(R.id.btn_getDirections);
		btn_dir.setOnClickListener(this);
		btn_addMe = (Button) findViewById(R.id.btn_AddMeAsADriverHere);
		btn_addMe.setOnClickListener(this);
		btn_post = (Button) findViewById(R.id.btn_post);
		btn_post.setOnClickListener(this);
		Button venmo = (Button)findViewById(R.id.btn_venmo);
		venmo.setOnClickListener(this);

		/* Get latitude longitude stuff */
		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		locationManager.requestLocationUpdates(
				LocationManager.GPS_PROVIDER, 
				MINIMUM_TIME_BETWEEN_UPDATES, 
				MINIMUM_DISTANCE_CHANGE_FOR_UPDATES,
				new MyLocationListener()
		);

		// Remove driver that have been created beyond 2 hours ago. 
		Connect myPzoneConnect = new Connect("http://m.cip.gatech.edu/developer/imf/api/RWMSERVER/pickupzoneinfo/");
		myPzoneConnect.AddParam("pzoneID", Integer.toString(pzoneID));
		try {
			myPzoneConnect.Execute(RequestMethod.POST);
			jObject = new JSONObject(myPzoneConnect.getResponse());
			/* Create Geopoint - Set position of the androidmarker */
			float lat = (float) jObject.getDouble("latitude");//33.7711f;//-23.4456f;
			float lng = (float) jObject.getDouble("longitude");//-84.3889f;//45.44334f;
			gp = new GeoPoint((int)(lat * 1E6), (int)(lng * 1E6));
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		//zoom
		mapController = mapView.getController();
		zoomOnLocation(gp);
		List<Overlay> mapOverlays = mapView.getOverlays();
		/* Get the marker */
		Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);

		/* Add the overlay (And overlay is just a layer you put over the map. In this case its just an android
		 * icon used to designate a zone locations. You can have an overlay to view  information, or and overlay
		 * to show population density, etc. ) */
		HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable,this);	
		OverlayItem overlayitem = new OverlayItem(gp, "Location", description);
		itemizedoverlay.addOverlay(overlayitem);
		mapOverlays.add(itemizedoverlay);
	}
	@Override
	protected boolean isRouteDisplayed()
	{
		return false;
	}

	public void onClick(View v) {
		Intent intent;
		switch (v.getId()){
		case R.id.btn_venmo:
			intent = new Intent(getApplicationContext(), VenmoActivity.class);
			intent.putExtra("pzoneID", pzoneID);
			startActivity(intent);
			break;
		case R.id.btn_getDirections:
			String path=null;
			Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);

			if (location != null) {
				path = String.format(
						"http://maps.google.com/maps?saddr=%1$s,%2$s&daddr=%3$s,%4$s",
						location.getLatitude(), location.getLongitude(),lat,lon 
				);
				Toast.makeText(ZoneDetailActivity.this, path,
						Toast.LENGTH_LONG).show();
			}

			intent = new Intent(android.content.Intent.ACTION_VIEW, 
					Uri.parse(path));
			startActivity(intent);
			//			Toast.makeText(ZoneDetailActivity.this, "test",
			//                    Toast.LENGTH_LONG).show();
			break;
		case R.id.btn_AddMeAsADriverHere:
			Connect connect = new Connect("http://m.cip.gatech.edu/developer/imf/api/RWMSERVER/updatedriverlist/");
			connect.AddParam("pzoneID", Integer.toString(pzoneID));
			connect.AddParam("access_token", access_token);
			
			try {
				connect.Execute(RequestMethod.POST);
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			break;

		case R.id.btn_post:
			EditText post = (EditText) findViewById(R.id.facebookPost);
			postToWall(post.getText().toString());
			break;
		}
	}

	private class MyLocationListener implements LocationListener {

		//		public void onLocationChanged(Location location) {
		//			String message = String.format(
		//					"New Location \n Longitude: %1$s \n Latitude: %2$s",
		//					location.getLongitude(), location.getLatitude()
		//			);
		//			Toast.makeText(ZoneDetailActivity.this, message, Toast.LENGTH_LONG).show();
		//		}

		//		public void onStatusChanged(String s, int i, Bundle b) {
		//			Toast.makeText(ZoneDetailActivity.this, "Provider status changed",
		//					Toast.LENGTH_LONG).show();
		//		}

		public void onProviderDisabled(String s) {
			Toast.makeText(ZoneDetailActivity.this,
					"Provider disabled by the user. GPS turned off",
					Toast.LENGTH_LONG).show();
		}

		public void onProviderEnabled(String s) {
			Toast.makeText(ZoneDetailActivity.this,
					"Provider enabled by the user. GPS turned on",
					Toast.LENGTH_LONG).show();
		}

		public void onStatusChanged(String provider, int status, Bundle extras) {
			// TODO Auto-generated method stub

		}

		public void onLocationChanged(Location location) {
			// TODO Auto-generated method stub

		}

	}
	private void zoomOnLocation(GeoPoint point) {
		mapController.animateTo(point);
		mapController.setZoom(16);
		//mapView.invalidate();
	}
	
	public void postToWall(String message){
		Bundle parameters = new Bundle();
                parameters.putString("message", message);
                parameters.putString("description", "topic share");
                try {
        	        facebook.request("me");
			String response = facebook.request("me/feed", parameters, "POST");
			Log.d("Tests", "got response: " + response);
			if (response == null || response.equals("") ||
			        response.equals("false")) {
				context.showToast("Blank response.");
			}
			else {
				context.showToast("Message posted to your facebook wall!");
			}
			finish();
		} catch (Exception e) {
			context.showToast("Failed to post to wall!");
			e.printStackTrace();
			finish();
		}
	}
}
